package main

import (
	"net/http"
	"io/ioutil"
	"encoding/json"
	"github.com/ngaut/log"
	"github.com/garyburd/redigo/redis"
	"github.com/kataras/iris/core/errors"
	"global/constants"
)

type bitZPrice struct {
	Code			int 				`json:"code"`
	Msg 			string 				`json:"msg"`
	Data 			map[string]string 	`json:"data"`
}

const bitZUrl = "https://api.bit-z.pro/api_v1/adprice"

func refreshPrice(ctx *Context) {

	defer func() {
		if err := recover(); err != nil {
			log.Infof("%v", err)
		}
	}()

	log.Infof("server run ....")

	conn := ctx.GetOteRedis().Get()
	defer conn.Close()

	price, err := httpGet(bitZUrl)
	if err != nil {
		log.Errorf("get bit-z price error, msg: %s", err.Error())
		return
	}

	if len(price) == 0 {
		log.Error("bit-z price return nil")
		return
	}

	for key, val := range price {
		if _, ok := CoinToCoinPrice[key]; ok {
			CoinToCoinPrice[key] = val
		}
	}

	_, err = conn.Do("HMSET", redis.Args{constants.CommonPriceKey}.AddFlat(CoinToCoinPrice)...)
	if err != nil {
		log.Errorf("hmset common price error, msg: %s", err.Error())
	}

	log.Debugf("set price success, price: %v", CoinToCoinPrice)
}

func httpGet(url string) (map[string]string, error) {
	defer func() {
		if p := recover(); p != nil {
			log.Errorf("p: %v", p)
		}
	}()
	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	var price bitZPrice
	err = json.Unmarshal(body, &price)
	if err != nil {
		return nil, err
	}

	if price.Code != 0 {
		return nil, errors.New(price.Msg)
	}

	return price.Data, nil
}